package com.qmrz.nb.project.alpubdb.controller;


import cn.hutool.core.date.DateUtil;
import com.qmrz.nb.common.util.MachineAvailabiltilyTools;
import com.qmrz.nb.framework.exception.ServiceException;
import com.qmrz.nb.framework.web.result.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.qmrz.nb.common.util.MachineFaultTools;
//import cn.quevo.xuanniao.core.exception.CustomException;
//import cn.quevo.xuanniao.spring.SpringController;
//import cn.quevo.xuanniao.spring.utils.WebUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.PoitlIOUtils;

/**
 * API 视图层
 * create by liang on 2022-01-04.
 */
@RestController
@Log4j2
public class ApiController {

    @GetMapping("/get/{testParam}")
    public R pageList(@PathVariable("testParam") String testParam) {
        return R.ok(testParam);
    }

    @PostMapping("upload")
    public void upload(  HttpServletResponse response, @RequestParam("preFile") MultipartFile preFile,
                         @RequestParam("curFile") MultipartFile curFile) throws
            IOException {
        if (preFile == null || curFile == null) {
            throw new ServiceException(6200, "文件内容不能为空");
        }
        String pm = Objects.requireNonNull(preFile.getOriginalFilename()).substring(0,1);
        String m = Objects.requireNonNull(curFile.getOriginalFilename()).substring(0,1);
        String method = Objects.requireNonNull(curFile.getOriginalFilename()).substring(0,2);
        String fileName = URLEncoder.encode(method+" 运一 附件2：二级公司月报" + ".docx", "utf-8").replaceAll("\\+", "%20");
//        HttpServletResponse response = WebUtils.getHttpServletResponse();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;filename=\""+fileName+"\"");
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy(true);
        Configure config = Configure.builder()
                .bind("merge", policy).build();
        MachineFaultTools tools = new MachineFaultTools();
        List<Map<String,String>> data = tools.merge(preFile.getName(), preFile.getInputStream(), curFile.getName(), curFile.getInputStream());


        Map<String, String> sumT = tools.mergeSum(data);
        int dataIndex = data.size()-1;
        sumT.put("diff10",data.get(dataIndex).get("diff10"));
        sumT.put("diff11",data.get(dataIndex).get("diff11"));
        sumT.put("diff12",data.get(dataIndex).get("diff12"));
        sumT.put("diff13",data.get(dataIndex).get("diff13"));
        sumT.put("diff14",data.get(dataIndex).get("diff14"));
        sumT.put("diff15",data.get(dataIndex).get("diff15"));
        sumT.put("diff16",data.get(dataIndex).get("diff16"));
        sumT.put("diff17",data.get(dataIndex).get("diff17"));
        sumT.put("diff18",data.get(dataIndex).get("diff18"));
        data.remove(dataIndex);
        List<Map<String,String>> data1 = tools.proportionHelp(data, sumT); // 补充占比字段
        Map<String, String> sumX = tools.proportionSumHelp(sumT , data1); // 补充环比字段

        MachineAvailabiltilyTools tools1 = new MachineAvailabiltilyTools();
        Map<String,String> data2 = tools1.merge(preFile.getName(), preFile.getInputStream(), curFile.getName(), curFile.getInputStream());

        // double b = 2.0; // 此处霏霏专用打断点处
        try(BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())){
            XWPFTemplate template = XWPFTemplate.compile(new ClassPathResource("templates/template.docx").getInputStream(), config).render(
                new HashMap<String, Object>(){{
                    put("t", sumX);
                    put("year", DateUtil.year(DateUtil.date()));
                    put("merge", data1);
                    put("info", data2);
                    put("method", method);
                    put("pm", pm);
                    put("m", m);
                }});
            template.write(bos);
            bos.flush();
            response.getOutputStream().flush();
            PoitlIOUtils.closeQuietlyMulti(template, bos, response.getOutputStream());
        }
    }



}




